package com.aaa.controller;


import com.aaa.entity.Goods;
import com.aaa.entity.Orders;
import com.aaa.mapper.GoodsMapper;
import com.aaa.mapper.OrdersMapper;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.log.Slf4JLogger;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api")
public class ApiController {


    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @GetMapping("/goods")
    public List<Goods> getGoods() {
        return goodsMapper.selectList();
    }

    @GetMapping("/orders")
    public List<Orders> getOrders() {
        return ordersMapper.selectList();
    }
    /**
     * 日志记录器对象
     */
    private static final Logger LOGGER= LoggerFactory.getLogger(ApiController.class);
    @Transactional
    @PostMapping("/buy")
    public boolean buy(@RequestParam Integer goodsId) {

        LOGGER.info("开始下单===="+goodsId);//使用该方法替代sout---因为这个输出可以记录到日志文件中。
        Goods goods = goodsMapper.selectById(goodsId);
        LOGGER.info("查询商品的信息:"+ JSON.toJSONString(goods));
        int store = goods.getStore() - 1;
        if (store < 0) {
            LOGGER.error("库存不足");
            return false;
        }
        Date date = new Date();
        Orders orders = new Orders();
        orders.setGoodsId(goodsId);
        orders.setCreateTime(date);
        orders.setName("购买" + goods.getName() + "订单");
        orders.setOrderId(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        orders.setTotal(goods.getPrice().multiply(BigDecimal.ONE));

        goods.setStore(store);
        return ordersMapper.insert(orders) > 0 &&  goodsMapper.updateById(goods) > 0;
    }
}
/**
 *  1.引入相关的依赖
 *  2.加入logback日志配置
 *  3.使用logback
 *      在相关的类中创建Logger对象
 *      使用该对象调用相应的方法: log("日志方法")  log.error("错误方法")
 */